package com.vf.admin.miaodong.controller;

import com.vf.admin.common.BaseController;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.miaodong.service.*;
import com.vf.admin.utils.Base64Image.FileUtil;
import com.vf.admin.utils.CheckSumBuilder;
import com.vf.admin.utils.StringEx;
import com.vf.admin.utils.WYIM.WYMsg;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 房间管理
 */
@Controller
@RequestMapping("/after/room")
public class AfterRoomController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static String appKey = "b3a4defaf7ab998efd263b44c40557e9";
    private static String appSecret = "7c832651e82a";
    @Autowired
    AfterRoomService afterRoomService;
    @Autowired
    AfterRoomTypeService afterRoomTypeService;
    @Autowired
    AfterRoomImgService afterRoomImgService;
    @Autowired
    AfterGameGiftRecordService afterGameGiftRecordService;
    @Autowired
    AfterGiftRewardService afterGiftRewardService;
    @Autowired
    AfterMingxiRoomService afterMingxiRoomService;
    /**
     * 房间管理列表
     *
     * @param splitPage
     * @return
     */
    @RequestMapping("/list")
    public String list(SplitPageBean splitPage, Integer status, String nick, String roomname,
                       String phone, String roomcode, String startDate, String endDate) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("nick", nick);
            map.put("roomname", roomname);
            map.put("phone", phone);
            map.put("roomcode", roomcode);
            map.put("status", status);
            map.put("startDate", startDate);
            map.put("endDate", endDate);

            List<AppRoom> list = afterRoomService.findList(map, splitPage);
            List<AppRoomType> roomtypeList = afterRoomTypeService.list(new HashMap<>(16),null);
            Map<Integer, String> getRoomstatusMap = Constants.getRoomstatusMap();
            Map<Integer, String> statusMap = Constants.getStatesMap();
            request.setAttribute("splitPage", splitPage);
            request.setAttribute("list", list);
            if (StringEx.isNotNull(status)) {
                request.setAttribute("status", status);
            }
            request.setAttribute("roomtypeList", roomtypeList);//房间类型
            request.setAttribute("getRoomstatusMap", getRoomstatusMap);//官方推荐
            request.setAttribute("statusMap", statusMap);//房间状态
            request.setAttribute("nick", nick);
            request.setAttribute("roomname", roomname);
            request.setAttribute("phone", phone);
            request.setAttribute("roomcode", roomcode);
            request.setAttribute("startDate", startDate);
            request.setAttribute("endDate", endDate);
            return this.sucess("/web/after/room/list");
        } catch (Exception e) {
            logger.error("获取房间管理列表异常", e);
            return this.error("系统繁忙");
        }
    }

    /**
     * 进入编辑房间详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    public String detail(Integer id) {
        try {
            Map<Integer, String> getRoomstatusMap = Constants.getRoomstatusMap();
            Map<Integer, String> statusMap = Constants.getStatesMap();
            AppRoom appRoom = afterRoomService.get(id);
            request.setAttribute("room", appRoom);
            request.setAttribute("getRoomstatusMap", getRoomstatusMap);//官方推荐
            request.setAttribute("statusMap", statusMap);//房间状态
            return this.sucess("/web/after/room/edit");
        } catch (Exception e) {
            logger.error("获取房间详情异常", e);
            return this.error("系统繁忙");
        }
    }

    /**
     * 编辑房间信息
     *
     * @param appRoom
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Result save(AppRoom appRoom) {
        try {
            if (StringEx.isNull(appRoom.getStatus())) {
                return this.errorJSON("状态不能为空");
            }
            if (StringEx.isNull(appRoom.getRoomstatus())) {
                return this.errorJSON("官方推荐不能为空");
            }
            if (StringEx.isNull(appRoom.getRoomtypeid())) {
                return this.errorJSON("房间类型不能为空");
            }
            if (StringEx.isNotNull(appRoom.getId())) {
                AppRoom appRoom1 = afterRoomService.get(appRoom.getId());
                appRoom1.setStatus(appRoom.getStatus());
                appRoom1.setRoomstatus(appRoom.getRoomstatus());
                appRoom1.setRoomtypeid(appRoom.getRoomtypeid());
                afterRoomService.save(appRoom1);
            }
            return this.sucessJSON("保存成功");
        } catch (Exception e) {
            logger.error("编辑房间信息异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    /**
     * 获取房间流水
     * @param splitPageBean
     * @param startDate  开始时间
     * @param endDate  结束时间
     * @param nick  用户名称
     * @param phone  用户电话
     * @param roomcode 房间编号
     * @return
     */
    @RequestMapping("/liushui")
    public String list(SplitPageBean splitPageBean,String startDate,String endDate,String nick,String phone,  String roomcode){
        try{
            Map<String,Object> map = new HashMap<>();
            map.put("startDate",startDate);
            map.put("endDate",endDate);
            map.put("nick",nick);
            map.put("phone",phone);
            map.put("roomcode",roomcode);
            List<AppMingxiRoom> list = afterMingxiRoomService.findList(map,splitPageBean);
            request.setAttribute("list",list);
            request.setAttribute("splitPage",splitPageBean);
            request.setAttribute("startDate",startDate);
            request.setAttribute("endDate",endDate);
            request.setAttribute("nick",nick);
            request.setAttribute("roomcode",roomcode);
            request.setAttribute("phone",phone);
            return this.sucess("/web/after/room/liushui");
        }catch (Exception e){
            logger.error("房间流水异常",e);
            return this.error("系统繁忙");
        }
    }


    /**
     * 房间详情信息
     *
     * @param roomid
     * @return
     */
    @RequestMapping("/roomDetail")
    public String roomDetail(Integer roomid) {
        try {
            AppRoom room=afterRoomService.get(roomid);

            request.setAttribute("room", room);

            return this.sucess("/web/after/room/listDetail");
        } catch (Exception e) {
            logger.error("获取房间详情异常", e);
            return this.error("系统繁忙");
        }
    }


    /**
     * 获取在线成员
     *
     * @param roomcode
     * @return
     */
    @RequestMapping("/online")
    public String online(String roomcode) {
        try {
            //获得固定成员
            String user = WYMsg.getRoomUser(roomcode, "2", "0", "100");
            JSONObject jsonObject = new JSONObject(user);
            List list = new ArrayList();
            if (jsonObject.get("code").equals(200)) {
                JSONArray list1 = jsonObject.getJSONObject("desc").getJSONArray("data");
                Map<String, Object> mapp = null;
                if (list1.length() > 0) {
                    for (int i = 0; i < list1.length(); i++) {
                        mapp = new HashMap<>();
                        JSONObject job = list1.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                        mapp.put("room", job.get("roomid"));
                        mapp.put("nick", job.get("nick"));
                        mapp.put("accid", job.get("accid"));
                        mapp.put("type", job.get("type"));
                        boolean onlineStat = (boolean) job.get("onlineStat");
                        String s = String.valueOf(onlineStat);
                        mapp.put("onlineStat", s);
                        mapp.put("avator", job.get("avator"));
                        list.add(mapp);
                    }
                }
            }
            request.setAttribute("list", list);

            return this.sucess("/web/after/room/onlineUser");
        } catch (Exception e) {
            logger.error("获取在线成员异常", e);
            return this.error("系统繁忙");
        }
    }

    /**
     * 禁用，解禁操作
     *
     * @param
     * @return
     */
    @RequestMapping("/jinyong")
    @ResponseBody
    public Result jinyong(String cid, Integer status) throws IOException {
        try {
            if (StringEx.isNull(cid)) {
                return this.errorJSON("获取直播频道ID为空");
            }
            Map map = new HashMap();
            System.out.println(cid + "-------" + status);
            if (status.equals(0)) {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String url = "https://vcloud.163.com/app/channel/resume";
                HttpPost httpPost = new HttpPost(url);
                String nonce = "1";
                String curTime = String.valueOf((new Date()).getTime() / 1000L);
                String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);//参考 计算CheckSum的java代码
                // 设置请求的header
                httpPost.addHeader("AppKey", appKey);
                httpPost.addHeader("Nonce", nonce);
                httpPost.addHeader("CurTime", curTime);
                httpPost.addHeader("CheckSum", checkSum);
                httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
                // 设置请求的参数
                StringEntity params = new StringEntity("{\"cid\":\"" + cid + "\"}", Consts.UTF_8);
                httpPost.setEntity(params);

                // 执行请求
                HttpResponse response = httpClient.execute(httpPost);
                String strResult = EntityUtils.toString(response.getEntity(), "utf-8");
                JSONObject jsonObject = new JSONObject(strResult);
                // 打印执行结果
//        System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
                Integer code = (Integer) jsonObject.get("code");

                if (code == 200) {
                    return sucess(map);
                }
                return errorJSON("系统繁忙");
            } else if (status.equals(2)) {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String url = "https://vcloud.163.com/app/channel/pause";
                HttpPost httpPost = new HttpPost(url);

                String nonce = "1";
                String curTime = String.valueOf((new Date()).getTime() / 1000L);
                String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);//参考 计算CheckSum的java代码

                // 设置请求的header
                httpPost.addHeader("AppKey", appKey);
                httpPost.addHeader("Nonce", nonce);
                httpPost.addHeader("CurTime", curTime);
                httpPost.addHeader("CheckSum", checkSum);
                httpPost.addHeader("Content-Type", "application/json;charset=utf-8");


                // 设置请求的参数
                StringEntity params = new StringEntity("{\"cid\":\"" + cid + "\"}", Consts.UTF_8);
                httpPost.setEntity(params);

                // 执行请求
                HttpResponse response = httpClient.execute(httpPost);
                String strResult = EntityUtils.toString(response.getEntity(), "utf-8");
                JSONObject jsonObject = new JSONObject(strResult);
                System.out.println(jsonObject);
                // 打印执行结果
//        System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
                Integer code = (Integer) jsonObject.get("code");

                if (code == 200) {
                    return sucessJSON(map);
                }
                return errorJSON("系统繁忙");
            }
            // 打印执行结果
//        System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));

            return this.sucessJSON("禁用成功");
        } catch (Exception e) {
            logger.error("禁用房间频道异常", e);
            return this.errorJSON("系统繁忙");
        }
    }


    //==========================房间背景管理============================

    /**
     * 房间背景图片列表
     *
     * @param splitPage 分页
     * @param leixing   类型
     * @return
     */
    @RequestMapping("/imglist")
    public String imglist(SplitPageBean splitPage, String leixing) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("leixing", leixing);
            List<AppRoomImg> list = afterRoomImgService.findList(map, splitPage);
            request.setAttribute("list", list);
            request.setAttribute("leixing", leixing);
            request.setAttribute("splitPage", splitPage);
            return this.sucess("/web/after/roomimg/list");
        } catch (Exception e) {
            logger.error("房间背景图片异常", e);
            return this.error("系统繁忙");
        }
    }

    /**
     * 删除用户个人背景
     *
     * @param idArray
     * @return
     */
    @RequestMapping("/imgdel")
    @ResponseBody
    public Result del(String idArray) {
        try {
            if (StringEx.isNull(idArray)) {
                return this.errorJSON("图片id不能为空");
            }
            String[] userIdArray = idArray.split(",");
            if (userIdArray != null && userIdArray.length > 0) {
                for (String id : userIdArray) {
                    if (StringEx.isNull(id)) {
                        continue;
                    }
                    AppRoomImg img = afterRoomImgService.get(Integer.valueOf(id));
                    if (img == null || img.getId() == null || img.getId() <= 0) {
                        return this.errorJSON("背景图片不存在!");
                    }
                    if (img.getLeixing()==1) {
                        return this.errorJSON("官方默认背景不允许删除!");
                    }
                    afterRoomImgService.del(img.getId());
                }
            }
            return this.sucessJSON("删除成功");
        } catch (Exception e) {
            logger.error("删除用户个人背景异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    /**
     * 添加官方背景跳转
     * @return
     */
    @RequestMapping("/imgadd")
    public String imgadd(){
        try{
            return this.sucess("/web/after/roomimg/add");
        }catch (Exception e){
            logger.error("添加官方背景跳转异常",e);
            return this.error("系统繁忙");
        }
    }

    /**
     * 编辑背景图片跳转
     * @param id id
     * @return
     */
    @RequestMapping("/imgdetail")
    public String imgdetail(Integer id){
        try{
            AppRoomImg img = afterRoomImgService.get(id);
            request.setAttribute("img",img);
            return this.sucess("/web/after/roomimg/edit");
        }catch (Exception e){
            logger.error("编辑背景图片跳转异常",e);
            return this.error("系统繁忙");
        }
    }
    /**
     * 新增背景图片
     * @param img 实体类
     * @return
     */
    @RequestMapping("/imgsave")
    @ResponseBody
    public Result imgsave(AppRoomImg img){
        try{

            if(StringEx.isNull(img.getUrl())){
                return this.errorJSON("图片不能为空");
            }

            if(img.getId() != null){
                AppRoomImg  roomImg = afterRoomImgService.get(img.getId());

                if(roomImg.getUrl().equals(img.getUrl())){
                    roomImg.setUrl(img.getUrl());
                }else{
                    //处理图片
                    String newfilePath = "";
                    Map map = FileUtil.aliyunOSSUpload(img.getUrl(),"");
                    if(map.get("st").equals("0")) {
                        newfilePath = (String)map.get("data");
                    }
                    if(StringEx.isNotNull(newfilePath)) {
                        roomImg.setUrl(newfilePath);
                    }
                }
                afterRoomImgService.save(roomImg);
            }else{
                Map<String,Object> maps=new HashMap<>(16);
                maps.put("leixing",1);
                List<AppRoomImg> imgList=afterRoomImgService.findList(maps,null);
                if(imgList.size()>0){
                    return this.errorJSON("官方背景图数量已达上限");
                }
                //处理图片
                String newfilePath = "";
                Map map = FileUtil.aliyunOSSUpload(img.getUrl(),"");
                if(map.get("st").equals("0")) {
                    newfilePath = (String)map.get("data");
                }
                if(StringEx.isNotNull(newfilePath)) {
                    img.setUrl(newfilePath);
                }
                img.setLeixing(1);
                img.setCreatetime(new Date());
                afterRoomImgService.save(img);
            }
            return this.sucessJSON("保存成功");
        }catch (Exception e){
            logger.error("编辑背景图片异常",e);
            return this.errorJSON("系统繁忙");
        }
    }
}
